package com.itzxx.huazhun.ui.user.audit

import android.text.TextUtils
import com.itzxx.huazhun.data.model.ApprovalUserInfo
import com.itzxx.huazhun.data.repository.HttpRequestCoroutine
import com.itzxx.library_base_ktx.base.viewmodel.BaseViewModel
import com.itzxx.library_base_ktx.callback.livedata.event.EventLiveData
import com.itzxx.library_base_ktx.ext.request
import com.itzxx.library_base_ktx.state.ListDataUiState
import com.itzxx.library_base_ktx.state.SingleListDataUiState

class AdministratorsAuditViewModel : BaseViewModel() {


    private var cursor: String = ""

    //列表数据刷新
    val listDataUiStateLiveData = EventLiveData<ListDataUiState<ApprovalUserInfo>>()

    //单条数据列表刷新
    val singleListDataUiStateLiveData = EventLiveData<SingleListDataUiState<ApprovalUserInfo>>()

    override fun onCreateViewModel() {
        super.onCreateViewModel()
        getList(true)
    }

    /**
     * 获取数据列表
     */
    fun getList(isRefresh: Boolean) {
        if (isRefresh) {
            cursor = ""
        }
        request({
            HttpRequestCoroutine.getUserAuditList(
                cursor
            )
        }, {
            val listDataUiState =
                ListDataUiState(
                    isSuccess = true,
                    isRefresh = isRefresh,
                    isEmpty = it.list.isEmpty(),
                    hasMore = !it.isLast,
                    isFirstEmpty = TextUtils.isEmpty(cursor) && it.list.isEmpty(),
                    listData = it.list
                )
            cursor = it.cursor
            listDataUiStateLiveData.postValue(listDataUiState)
        }, {
            toast(it.errorMsg)
        })
    }

    /**
     * 审核动作处理
     */
    fun doUserAuditHandle(
       approvalUserInfo: ApprovalUserInfo,
       approvalStatus:Int,
        position: Int
    ) {
        loadingChange.showDialog.postValue("处理中...")
        request({
            HttpRequestCoroutine.doUserAuditHandle(
                approvalUserInfo.id,
                approvalUserInfo.applicationName,
                approvalStatus,
                approvalUserInfo.refuseRemark,
            )
        }, {
            loadingChange.dismissDialog.postValue(false)
            approvalUserInfo.approvalStatus = approvalStatus
            val singleListDataUiState = SingleListDataUiState(position, approvalUserInfo)
            singleListDataUiStateLiveData.postValue(singleListDataUiState)
        }, {
            loadingChange.dismissDialog.postValue(false)
            toast(it.errorMsg)
        })
    }
}